package com.minshenglife.zanzan.web.manage;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.entity.power.EmpPower;
import com.minshenglife.zanzan.entity.power.GroupPower;
import com.minshenglife.zanzan.entity.power.MUserPower;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.service.GroupPowerService;
import com.minshenglife.zanzan.service.UserService;
import com.minshenglife.zanzan.service.WorkConPowerService;
import com.minshenglife.zanzan.service.power.EmpPowerService;
import com.minshenglife.zanzan.service.power.MUserPowerService;
import com.minshenglife.zanzan.web.manage.cst.ManageKeys;

/**
 * 工作日志权限controller
 * 
 * @author jianghaibo
 *
 */
@Controller
@RequestMapping("/workConPower")
public class WorkConPowerController {
	Logger log = LoggerFactory.getLogger(WorkConPowerController.class);

	@Resource
	WorkConPowerService workConPowerService;
	
	@Resource
	UserService userService;
	
	@Resource
	GroupPowerService groupPowerService;

	@Resource
	EmpPowerService empPowerService;
	
	@Autowired
	MUserPowerService mUserPowerService;
	
	/**
	 * 保存权限
	 * @param request
	 * @param response
	 * @param empIds
	 * @param powerType
	 * @return
	 */
	@RequestMapping(value = "/save.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message save(HttpServletRequest request,
			HttpServletResponse response, String[] empIds, String powerType) {
		Message message = new Message(Message.STATE_200);
		String notExistEmpNo = null;
		try {
			System.out.println("empIds-->"+empIds);
			System.out.println("powerType-->"+powerType);
			String notExistemp = workConPowerService.save(empIds,powerType);
			if(!notExistemp.equals("")){
				message.setMsg("保存成功，但员工号为“"+notExistemp+"”的员工不存在，请核对。");
				message.setData(notExistemp);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	/**
	 * 删除权限
	 * @param request
	 * @param response
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message delete(HttpServletRequest request,
			HttpServletResponse response, String[] ids) {
		Message message = new Message(Message.STATE_200);
		try {
			workConPowerService.delete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	/**
	 * 获取某权限类型中的人员列表
	 * @param request
	 * @param response
	 * @param powerType
	 * @return
	 */
	@RequestMapping(value = "/findEmpByPowerType.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message findEmpByPowerType(HttpServletRequest request,
			HttpServletResponse response, String powerType) {
		Message message = new Message(Message.STATE_200);
		try {
			List<User> list = workConPowerService.findEmpListByPowerType(powerType);
			message.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	@RequestMapping(value = "/findEmpListByPowerType.mge", method = RequestMethod.GET)
	public String findEmpByPowerTypePage(ModelMap modeMap, String powerType,HttpServletRequest request,
			HttpServletResponse response) {
		try {
			List<User> list = workConPowerService.findEmpListByPowerType(powerType);
			modeMap.put("powerType", powerType);
			modeMap.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/jsp/manage/workConPowerList";
	}
	
	@RequestMapping(value = "/toAddPage.mge", method = RequestMethod.GET)
	public String toAddPage(ModelMap modeMap, String powerType,HttpServletRequest request,
			HttpServletResponse response) {
			modeMap.put("powerType", powerType);
		return "/jsp/manage/workConPowerAdd";
	}

	@RequestMapping(value = "/findManagerGroup.mge", method = RequestMethod.GET)
	public String findManagerGroup(ModelMap modeMap,HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Map<String,String> groupMap = groupPowerService.findAllGroupPower();
			modeMap.put("groups", groupMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/jsp/manage/workConManagerGroup";
	}
	
	/**
	 * 根据主权限删除权限组
	 * @param request
	 * @param response
	 * @param viewEmp
	 * @return
	 */
	@RequestMapping(value = "/deleteManagerGroup.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message deleteManagerGroup(HttpServletRequest request,
			HttpServletResponse response, String viewEmp) {
		Message message = new Message(Message.STATE_200);
		try {
			String viewEmpId = viewEmp.substring(0,viewEmp.indexOf("("));
			groupPowerService.deleteViewEmpId(viewEmpId);
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	/**
	 * 
	 * @param modeMap
	 * @param powerType
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateGroupPower.mge", method = RequestMethod.GET)
	public String updateGroupPower(ModelMap modeMap, String viewEmp,HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Map<String,String> groupMap = groupPowerService.findGroupPowerByViewEmpId(viewEmp);
			modeMap.put("groups", groupMap);
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return "/jsp/manage/workConManagerGroupUpdate";
	}
	
	@RequestMapping(value = "/updateGroupManagerByViewEmp.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message updateGroupManagerByViewEmp(ModelMap modeMap, String viewEmp,String beViewEmpIds,HttpServletRequest request,
			HttpServletResponse response) {
		Message message = new Message(Message.STATE_200);
		try {
			log.info(viewEmp);
			log.info(beViewEmpIds);
			String[] viewEmpIds = viewEmp.split("\\|");
			String errorMsg = "";
			for(String thisViewEmpId:viewEmpIds){
				thisViewEmpId = thisViewEmpId.trim();
				if(thisViewEmpId.length()==0){
					continue;
				}
				String viewEmpId = thisViewEmpId;
				if(thisViewEmpId.contains("(")){
					viewEmpId = thisViewEmpId.substring(0,thisViewEmpId.indexOf("("));
				}
				User userViewEmp = userService.getEmpUser(viewEmpId);
				if(userViewEmp==null){
					errorMsg+="该用户："+viewEmpId+"非我公司用户，禁止授予权限！";
					continue;
				}
				groupPowerService.deleteViewEmpId(viewEmpId);
				if(beViewEmpIds.contains("ALL")){
					if(userViewEmp.getPostId().trim().toUpperCase().equals("S")){
						GroupPower gp = new GroupPower();
						gp.setViewEmpId(viewEmpId);
						gp.setBeViewEmpId("ALL");
						
						log.info("开始插入数据:"+viewEmpId+"拥有全部权限日志");
						groupPowerService.add(gp);
					}else{
						message = new Message(Message.STATE_one, viewEmpId+"不是公司S级领导，不能拥有全部权限");
						return message;
					}			
				}else{
					String[] strs = beViewEmpIds.trim().split("\\|");
					for(int i=0;i<strs.length;i++){
						log.info("========================"+i);
						String beViewEmpId = strs[i].trim();
						if(beViewEmpId.contains("(")){
							beViewEmpId = beViewEmpId.substring(0,beViewEmpId.indexOf("("));
						}
						beViewEmpId = beViewEmpId.trim();
						
						if(beViewEmpId.length()==0)
							continue;
						User user = userService.getUserInfo(beViewEmpId);
						System.out.println(user==null);
						if(user==null){
							errorMsg+=viewEmpId+"下的员工："+beViewEmpId+"非公司员工；";
							continue;
						}
						GroupPower gp = new GroupPower();
						gp.setViewEmpId(viewEmpId);
						gp.setBeViewEmpId(beViewEmpId);
						
						log.info("开始插入数据"+i+":"+viewEmpId+","+beViewEmpId);
						groupPowerService.add(gp);
					}
				}
			}
			
			if(errorMsg.trim().length()==0){
				errorMsg = "操作成功！";
			}
			message.setMsg(errorMsg);
				
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}	
		return message;
	}
	
	@RequestMapping(value = "/addGroupManagerByViewEmp.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message addGroupManagerByViewEmp(ModelMap modeMap, String viewEmpId,String beViewEmpIds,HttpServletRequest request,
			HttpServletResponse response) {
		Message message = new Message(Message.STATE_200);
		try {
			log.info(viewEmpId);
			log.info(beViewEmpIds);
			String[] viewEmpIds = viewEmpId.split("\\|");
			String errorMsg = "";
			for(String thisViewEmpId:viewEmpIds){
				thisViewEmpId = thisViewEmpId.trim();
				if(thisViewEmpId.length()==0){
					continue;
				}
				if(thisViewEmpId.contains("(")){
					thisViewEmpId = thisViewEmpId.substring(0,thisViewEmpId.indexOf("("));
				}
				User userViewEmp = userService.getEmpUser(thisViewEmpId);
				if(userViewEmp==null){
					errorMsg+="该用户："+thisViewEmpId+"非我公司用户，禁止授予权限！";
					continue;
				}
				groupPowerService.deleteViewEmpId(thisViewEmpId);
				if(beViewEmpIds.contains("ALL")){
					if(userViewEmp.getPostId().trim().toUpperCase().equals("S")){
						GroupPower gp = new GroupPower();
						gp.setViewEmpId(viewEmpId);
						gp.setBeViewEmpId("ALL");
						
						log.info("开始插入数据:"+viewEmpId+"拥有全部权限日志");
						groupPowerService.add(gp);
					}else{
						message = new Message(Message.STATE_one, viewEmpId+"不是公司S级领导，不能拥有全部权限");
						return message;
					}			
				}else{
					String[] strs = beViewEmpIds.trim().split("\\|");
					for(int i=0;i<strs.length;i++){
						log.info("========================"+i);
						String beViewEmpId = strs[i].trim();
						if(beViewEmpId.contains("(")){
							beViewEmpId = beViewEmpId.substring(0,beViewEmpId.indexOf("("));
						}
						beViewEmpId = beViewEmpId.trim();
						
						if(beViewEmpId.length()==0)
							continue;
						
						User user = userService.getEmpUser(beViewEmpId);
						System.out.println(user==null);
						if(user==null){
							errorMsg+=thisViewEmpId+"下的员工："+beViewEmpId+"非公司员工；";
							continue;
						}
						
						GroupPower gp = new GroupPower();
						gp.setViewEmpId(thisViewEmpId);
						gp.setBeViewEmpId(beViewEmpId);
						
						log.info("开始插入数据"+i+":"+thisViewEmpId+","+beViewEmpId);
						groupPowerService.add(gp);
					}
				}
			}
			if(errorMsg.trim().length()==0){
				errorMsg = "操作成功！";
			}
			message.setMsg(errorMsg);
				
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}	
		return message;
	}
	
	@RequestMapping(value = "/findEmpPowerList.mge", method = RequestMethod.GET)
	public String findEmpPowerPage(ModelMap modeMap, String type, String power,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			List<EmpPower> list = empPowerService.getEmpPowerList(null, power,
					type);
			modeMap.put("power", power);
			modeMap.put("type", type);
			modeMap.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/jsp/manage/EmpPowerList";
	}
	
	
	@RequestMapping(value = "/deleteEmpPower.mge", method = RequestMethod.GET)
	public String deleteEmpPowerPage(ModelMap modeMap, String type,String power,HttpServletRequest request,
			HttpServletResponse response) {
		try {
			List<EmpPower> list = empPowerService.getEmpPowerList(null, power, type);
			modeMap.put("power", power);
			modeMap.put("type", type);
			modeMap.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/jsp/manage/EmpPowerList";
	}
	
	@RequestMapping(value = "/toAddEmpPower.mge", method = RequestMethod.GET)
	public String toAddEmpPowerPage(ModelMap modeMap, String type,String power,HttpServletRequest request,
			HttpServletResponse response) {
			modeMap.put("power", power);
			modeMap.put("type", type);
			return "/jsp/manage/EmpPowerAdd";
	}	
	
	@RequestMapping(value = "/saveEmpPower.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message saveEmpPower(HttpServletRequest request,
			HttpServletResponse response, String[] empIds, String power,
			String type) {
		Message message = new Message(Message.STATE_200);
		String notExistEmpNo = null;
		try {
			System.out.println("empIds-->" + empIds);
			System.out.println("power-->" + power);
			System.out.println("type-->" + type);
			String notExistemp = empPowerService.save(empIds, power, type);
			if (!notExistemp.equals("")) {
				message.setMsg("保存成功，但员工号为“" + notExistemp + "”的员工不存在，请核对。");
				message.setData(notExistemp);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	@RequestMapping(value = "/deleteEmpPower.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message deleteEmpPower(HttpServletRequest request,
			HttpServletResponse response, String empId,String type,String power) {
		Message message = new Message(Message.STATE_200);
		try {
			if(StringUtils.isEmpty(empId)||StringUtils.isEmpty(type)||StringUtils.isEmpty(power)){
				message = new Message(Message.STATE_one, "参数异常");
			}
			empPowerService.delete(empId, power, type);
			message.setMsg("操作成功！");
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	@RequestMapping(value = "/updatePassword.mge", method = RequestMethod.GET)
	public String updatePasswordPage(HttpServletRequest request,
			HttpServletResponse response) {
		return "/jsp/manage/updatePassword";
	}
	
	/**
	 * 根据主权限删除权限组
	 * @param request
	 * @param response
	 * @param viewEmp
	 * @return
	 */
	@RequestMapping(value = "/updatePassword.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message updatePassword(HttpServletRequest request,
			HttpServletResponse response,@RequestParam String password,@RequestParam String passwordConfirm,HttpSession session) {
		Message message = new Message(Message.STATE_200);
		try {
			if(password!=null&&password.trim().length()>=8){//密码不得低于8为数
				if(password.equals(passwordConfirm)){
					MUserPower user = (MUserPower)session.getAttribute(ManageKeys.SESSION_USER_KEY);
					user.setPassword(toMD5(password.trim()));
					boolean flag = mUserPowerService.updateMUserPower(user);
					if(flag){
						message.setMsg("密码重置成功，请重新登录！");
						request.getSession(true).removeAttribute(ManageKeys.SESSION_USER_KEY);//重新登录操作
					}else{
						message.setState(Message.STATE_one);
						message.setMsg("密码重置失败，请重新输入！");
					}
					
				}else{
					message.setState(Message.STATE_one);
					message.setMsg("两次密码不一致，请重新输入！");
				}
			}else{
				message.setState(Message.STATE_one);
				message.setMsg("密码位数不得低于8位，请重新输入！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	private String toMD5(String password){
		// md5 encrypt
		MessageDigest md5;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			md5 = MessageDigest
					.getInstance("MD5");
			md5.update(password.getBytes());
			byte[] domain = md5.digest();
			// converting domain to String
			for (int i = 0; i < domain.length; i++) {
				if (Integer.toHexString(0xFF & domain[i]).length() == 1) {
					md5StrBuff.append("0").append(
							Integer.toHexString(0xFF & domain[i]));
				} else
					md5StrBuff.append(Integer.toHexString(0xFF & domain[i]));
			}
			System.out.println(md5StrBuff.toString());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md5StrBuff.toString();
	}
	
	@RequestMapping(value = "/selectManagerUserPage.mge", method = RequestMethod.GET)
	public String selectManagerUserPage(HttpServletRequest request,
			HttpServletResponse response,ModelMap model) {
		MUserPower user = new MUserPower();
		List<MUserPower> list = mUserPowerService.getMUserPowers(user);
		model.addAttribute("list", list);
		return "/jsp/manage/selectManagerUserPage";
	}
	
	@RequestMapping(value = "/selectManagerUser.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message selectManagerUser(HttpServletRequest request,
			HttpServletResponse response) {
		Message message = new Message(Message.STATE_200);
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	@RequestMapping(value = "/deleteManagerUser.mge", method = RequestMethod.POST)
	@ResponseBody
	public Message deleteManagerUser(HttpServletRequest request,
			HttpServletResponse response,@RequestParam String userName) {
		Message message = new Message(Message.STATE_200);
		try {
			if(userName==null||userName.trim().length()==0){
				message = new Message(Message.STATE_one,"用户名不能为空！");
				return message;
			}
			MUserPower user = new MUserPower();
			user.setUserName(userName);
			boolean flag = mUserPowerService.deleteMUserPower(user);
			if(flag){
				message.setMsg("用户删除成功！");
				return message;
			}else{
				message = new Message(Message.STATE_one,"用户删除失败！");
				return message;
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	@RequestMapping(value="/updateManagerUser.mge",method=RequestMethod.GET)
	public String updateManagerUser(ModelMap model,@RequestParam String userName,HttpServletRequest request,
			HttpServletResponse response){
		try{
			if(userName==null||userName.trim().length()==0){
				return "/jsp/manage/error";
			}
			MUserPower user = new MUserPower();
			user.setUserName(userName.trim());
			List<MUserPower> users = mUserPowerService.getMUserPowers(user);
			if(users.size()!=1){
				return "/jsp/manage/error";
			}
			user = users.get(0);
			model.addAttribute("muser",user);
			return "/jsp/manage/updateUserPassword";
		}catch(Exception ex){
			ex.printStackTrace();
			return "/jsp/manage/error";
		}
	}
	
	@RequestMapping(value="/updateUserPassword.mge",method=RequestMethod.POST)
	@ResponseBody
	public Message updateUserPassword(@RequestParam String userName,@RequestParam String password,@RequestParam String passwordConfirm){
		Message message = new Message(Message.STATE_200);
		try {
			if(userName==null||userName.trim().length()==0){
				message.setState(Message.STATE_one);
				message.setMsg("用户名不能为空！");
				return message;
			}
			if(password!=null&&password.trim().length()>=8){//密码不得低于8为数
				if(password.equals(passwordConfirm)){
					MUserPower user = new MUserPower();
					user.setUserName(userName.trim());
					user.setPassword(toMD5(password.trim()));
					boolean flag = mUserPowerService.updateMUserPower(user);
					if(flag){
						message.setMsg("密码重置成功！");
					}else{
						message.setState(Message.STATE_one);
						message.setMsg("密码重置失败，请重新输入！");
					}
					
				}else{
					message.setState(Message.STATE_one);
					message.setMsg("两次密码不一致，请重新输入！");
				}
			}else{
				message.setState(Message.STATE_one);
				message.setMsg("密码位数不得低于8位，请重新输入！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
	
	@RequestMapping(value = "/toAddMangerUser.mge", method = RequestMethod.GET)
	public String toAddMangerUser(HttpServletRequest request,
			HttpServletResponse response,ModelMap model) {
		return "/jsp/manage/addManagerUser";
	}
	
	@RequestMapping(value="/addManagerUser.mge",method=RequestMethod.POST)
	@ResponseBody
	public Message addManagerUser(MUserPower user,@RequestParam String passwordConfirm){
		Message message = new Message(Message.STATE_200);
		try {
			if(user==null){
				message.setState(Message.STATE_one);
				message.setMsg("数据为空，不能添加用户！");
				return message;
			}
			if(user.getUserName()==null||user.getUserName().trim().length()==0){
				message.setState(Message.STATE_one);
				message.setMsg("用户名不能为空！");
				return message;
			}
			user.setUserName(user.getUserName().trim());
			if(user.getIsAdmin()==null||user.getIsAdmin().trim().length()!=1){
				message.setState(Message.STATE_one);
				message.setMsg("管理员类型错误！");
				return message;
			}
			if(user.getComId()==null||user.getComId().trim().length()==0){
				message.setState(Message.STATE_one);
				message.setMsg("所属公司不能为空！");
				return message;
			}
			if(user.getPassword()!=null&&user.getPassword().trim().length()>=8){//密码不得低于8为数
				if(user.getPassword().equals(passwordConfirm)){
					//判断用户名是否已存在
					user.setPassword(toMD5(user.getPassword().trim()));
					MUserPower tmp = new MUserPower();
					tmp.setUserName(user.getUserName());
					List<MUserPower> list = mUserPowerService.getMUserPowers(tmp);
					if(list==null||list.size()==0){
						boolean flag = mUserPowerService.addMUserPower(user);
						if(flag){
							message.setMsg("添加用户成功！");
						}else{
							message.setState(Message.STATE_one);
							message.setMsg("添加用户失败！");
						}
					}else{
						message.setState(Message.STATE_one);
						message.setMsg("用户名已存在，请重新输入！");
					}
					
					
					
					
				}else{
					message.setState(Message.STATE_one);
					message.setMsg("两次密码不一致，请重新输入！");
				}
			}else{
				message.setState(Message.STATE_one);
				message.setMsg("密码位数不得低于8位，请重新输入！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one, "服务器异常");
			log.debug(message.toString());
		}
		return message;
	}
}
